package Demo.Controller;

import Demo.Uti.DatabaseUtil;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class LoginRegistrationApp extends Application {

    @Override
    public void start(Stage primaryStage) {
//        设置布局
        GridPane grid = new GridPane();
        grid.setHgap(10);
        grid.setVgap(10);
        grid.setPadding(new Insets(20));//内边距

//        登陆页面相应的标签
        Label userLabel = new Label("用户名字:");
        TextField userTextField = new TextField();
        Label passLabel = new Label("密码:");
        PasswordField passField = new PasswordField();
        Button loginButton = new Button("登陆");
        Button registerButton = new Button("注册");
        Label statusLabel = new Label();

//        设置标签的行与列索引
        grid.add(userLabel, 0, 0);
        grid.add(userTextField, 1, 0);
        grid.add(passLabel, 0, 1);
        grid.add(passField, 1, 1);
        grid.add(loginButton, 1, 2);
        grid.add(registerButton, 1, 3);
        grid.add(statusLabel, 1, 4);


        Scene scene = new Scene(grid, 300, 200);
        primaryStage.setTitle("图书管理系统登陆界面");
        primaryStage.setScene(scene);
        primaryStage.show();

        loginButton.setOnAction(e -> {
            String username = userTextField.getText();
            String password = passField.getText();
            if (login(username, password)) {
                statusLabel.setText("登陆成功!");
                Connection conn = null;
                try {
                    conn = DatabaseUtil.getConnection();
                } catch (SQLException ex) {
                    throw new RuntimeException(ex);
                }

                new BookManagementUI(conn).show();
            } else {
                statusLabel.setText("密码或账号不正确!");
            }
        });

        registerButton.setOnAction(e -> {
            String username = userTextField.getText();
            String password = passField.getText();
            if (register(username, password)) {
                statusLabel.setText("注册成功!");
            } else {
                statusLabel.setText("注册失败!");
            }
        });


    }

    private boolean login(String username, String password) {
        // 与数据库交互的登录逻辑
        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement("SELECT * FROM users WHERE username = ? AND password = ?")) {
            stmt.setString(1, username);
            stmt.setString(2, password); // 注意：实际应用中应该使用密码散列
            try (ResultSet rs = stmt.executeQuery()) {
                if (rs.next()) {
                    // 登录成功，显示图书管理界面
                    // 创建一个新的Stage实例来展示图书管理界面
                    Stage bookManagementStage = new Stage();
                    // 创建BookManagementUI实例并传入Stage和数据库连接
                    BookManagementUI bookManagementUI = new BookManagementUI(conn);
                    // 启动图书管理界面
                    bookManagementUI.show();
                    // 显示Stage
                    bookManagementStage.show();
                    return true;
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    private boolean register(String username, String password) {
        // 检查用户名是否已存在
        String checkSql = "SELECT EXISTS(SELECT * FROM users WHERE username = ?)";
        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(checkSql)) {
            stmt.setString(1, username);
            try (ResultSet rs = stmt.executeQuery()) {
                if (rs.next() && rs.getInt(1) == 0) {
                    // 用户名不存在，可以注册
                    String sql = "INSERT INTO users (username, password) VALUES (?, ?)";
                    try (PreparedStatement insertStmt = conn.prepareStatement(sql)) {
                        insertStmt.setString(1, username);
                        insertStmt.setString(2, password); // 注意：实际应用中应该使用密码散列
                        return insertStmt.executeUpdate() > 0;
                    }
                }
                return false;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    public static void main(String[] args) {
        launch(args);
    }
}